<template>
  <div class="bgc_white" id="register">
    <div  class="betaTester">
      <el-form :model="form" :rules="rules" ref="form">
        <p class="title">Beta Tester Program</p>
        <p class="secTitleGuide">{{$t('WARRANTY.WARRANTYLOGIN')}}<span @click="goToLogIn">{{$t('DEFAULT.SIGNIN')}} ></span></p>
        <p class="secTitle">{{$t('DEFAULT.BTTITLE')}}</p>
        <p class="formTitle">{{$t('DEFAULT.BTEMAILADDRESS')}}</p>
         <el-form-item  prop="email">
          <el-input  v-model="form.email"  @keyup.enter.native="getEmailStatus" @blur="getEmailStatus"></el-input >
        </el-form-item>
        <p class="formTitle">{{$t('DEFAULT.BTCOUNTRY')}}</p>
        <el-form-item  prop="country">
          <el-select v-model="form.country" placeholder=""> 
            <el-option v-for="item in countryList" :key="item.name_en" :value="item.name_en" :label="item.name_en"></el-option>
          </el-select>
        </el-form-item>
        <p class="formTitle">{{$t('DEFAULT.BTUSERNAME')}}</p>
        <el-form-item  prop="nickname">
          <el-input  v-model="form.nickname"  ></el-input>
        </el-form-item>
        
        <p class="formTitle">{{$t('DEFAULT.BTUSE')}}</p>
        <el-form-item  prop="active_device" placeholder="">
          <el-select v-model="form.active_device" multiple placeholder=""> 
            <el-option v-for="item in curUseList" :key="item.value"  :value="item.value" :label="$t('DEFAULT.'+item.label)"></el-option>
          </el-select>
        </el-form-item>
        <p class="formTitle">{{$t('DEFAULT.BTTEST')}}</p>
        <el-form-item  prop="evaluate_products">
          <el-select v-model="form.evaluate_products"  multiple placeholder="" @change="changeEvaluate"> 
            <el-option v-for="item in testProductList" :key="item.value" :value="item.value" :label="$t('DEFAULT.'+item.label)"></el-option>
          </el-select>
        </el-form-item>
          <p class="formTitle">{{$t('DEFAULT.BTOPINION')}}</p>
        <el-form-item  prop="is_share_ideas">
          <el-select v-model="form.is_share_ideas" placeholder=""> 
            <el-option v-for="item in isShareList" :key="item.value" :value="item.value" :label="$t('DEFAULT.'+item.label)"></el-option>
          </el-select>
        </el-form-item>
          <p class="formTitle">{{$t('DEFAULT.BTINFO')}}</p>
        <el-form-item  prop="is_kept_confidential">
          <el-select v-model="form.is_kept_confidential" placeholder=""> 
            <el-option v-for="item in isShareList " :key="item.value" :value="item.value" :label="$t('DEFAULT.'+item.label)"></el-option>
          </el-select>
        </el-form-item>

        <p class="formTitle" v-show="curEmail.sign_up == 0">{{$t('DEFAULT.PASSWORD')}} </p>
        <el-form-item v-show="curEmail.sign_up == 0"  prop="password">
          <el-input  v-model="form.password"  :type="showPsw" >
            <i @click="isPswShow" slot="suffix" :class="showPsw == 'password' ? 'icon-nondisplay_normal iconfont': 'iconfont icon-display_normal'  "></i>
          </el-input>
        </el-form-item>
        <p class="formTitle" v-show="curEmail.sign_up == 0">{{$t('DEFAULT.CONFIRMPSW')}} </p>
        <el-form-item  prop="confirmPwd" v-show="curEmail.sign_up == 0">
          <el-input  v-model="form.confirmPwd"  :type="showConfirmPsw">
            <i @click="isConfirmPswShow" slot="suffix" :class="showConfirmPsw == 'password' ? 'icon-nondisplay_normal iconfont': 'iconfont icon-display_normal'  "></i>
          </el-input>
        </el-form-item>

        <el-button @click="submitForm()"  :loading="isRequest" :class="{'isFull': isFull}">{{$t('DEFAULT.SIGNUP')}}</el-button>
      </el-form>
      <el-dialog :close-on-click-modal="false"   :visible.sync="isInfoShow" class="warranty_dialog">
        <div class="warranty_dialog_content" v-if="!userInfo.email">
          <p>{{$t('BETATESTER.ACCOUNTLOGIN')}}</p>
        </div>
        <div class="warranty_dialog_content" v-else>
          <p>{{$t('BETATESTER.ACCOUNT')}}</p>
          <p>{{$t('BETATESTER.CHECKDEVICE')}}</p>
        </div>
        <span slot="footer" class="dialog-footer">
          <router-link to="/login" v-if="!userInfo.email"><el-button type="search" >Sign in</el-button></router-link>
           <router-link to="/my_benefits" v-else><el-button type="search" >My Benefits</el-button></router-link>
        </span>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" :visible.sync="isGuideShow" class="warranty_dialog">
        <div class="warranty_dialog_content">
          <p>{{$t('BETATESTER.ACCOUNT')}}</p>
          <p>{{$t('BETATESTER.CHECKDEVICE')}}</p>
        </div>
        <span slot="footer" class="dialog-footer">
          <router-link :to="{path:'/betatester_active',query:{email: form.email}}"><el-button type="search" class="btnWidth" >Subscribe Beta Tester</el-button></router-link>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { betaTester } from '@/api/register.js'
import { mapGetters } from 'vuex'
import { allEmailGet } from '@/api/contactUs'
import { timeFormat } from '@/utils/index.js'
export default {
  data () {
    const validatePsw = (rule, value, callback) => {
      if (value === '' || value.length < 6 || value.length > 12) {
        callback(new Error(this.$t('DEFAULT.MSGPWSLEN')));
      } else if (this.form.password && this.form.confirmPwd && this.form.password  !== this.form.confirmPwd) {
        callback(new Error(this.$t('DEFAULT.MSGOSWDIFF')))
      } else {
        callback()
      }
    };
    return {
      isGuideShow: false,
      isInfoShow: false,
      isRequest: false,
      showPsw: 'password',
      showConfirmPsw: 'password',
      emailList: [],
      curEmail: {
        sign_up: 1
      },
      form:{
        country: '',
        nickname : '',
        email: '',
        active_device: '',
        is_share_ideas: '',
        is_kept_confidential: '',
        evaluate_products: '',
        password: '',
        confirmPwd: ""
      },
      curUseList: [
        {value:'USB-C Devices', label: 'BTUSEU'},
        {value:'Micro-USB Devices', label: 'BTUSEM'},
        {value:'MacBook Pro before 2016', label: 'BTUSEMB'},
        {value:'iPhone/Lightning Devices', label: 'BTUSEI'},
        {value:'Other', label: 'BTUSEO'},
      ],
      testProductList: [
        {value:'Lightning Cables for Apple Devices', label: 'BTTESTL'},
        {value:'Adapters', label: 'BTTESTA'},
        {value:'Chargers & Power Banks', label: 'BTTESTC'},
        {value:'Micro-USB Cables', label: 'BTTESTM'},
        {value:'Crowdfunding Products', label: 'BTTESTCP'},
        {value:'USB-C Cables', label: 'BTTESTU'},
        {value:'Other', label: 'BTTEOTHER'},
        
      ],
      isShareList: [
        {value:'Yes', label: 'BTYES'},
        {value:'No', label: 'BTNO'},
      ],
      rules: {
        country: [
          { required: true, message: 'country is required', trigger: 'change' }
        ],
        nickname: [
          { required: true, message: 'User Name is required', trigger: 'change' }
        ],
        email: [
          { required: true, message: 'Email Address is required', trigger: 'blur' },
          { type: 'email', message:  this.$t('DEFAULT.CORRECTEMAIL'), trigger: 'blur' }
        ],
        active_device: [
          { required: true, message: "I'm currently using is required", trigger: 'blur' }
        ],
        is_share_ideas: [
          { required: true, message: "Are you willing to share us with your opinions? is required ", trigger: 'blur' }
        ],
        is_kept_confidential: [
          { required: true, message: "Can you keep product information confidential? is required", trigger: 'blur' }
        ],
        evaluate_products: [
          { required: true, message: "I'm interested in beta testing is required", trigger: 'blur' }
        ],
        password: [
          { required: true,trigger: 'blur',  validator: validatePsw },
          { min: 6, max: 12, message: this.$t('DEFAULT.MSGPWSLEN'), trigger: 'blur' }
        ],
        confirmPwd: [
          { required: true, trigger: 'blur' , validator: validatePsw},
          { min: 6, max: 12,  trigger: 'blur' }
        ]
      
      }
    }
  },
   computed: {
    ...mapGetters(['siteList', 'userInfo', 'curSite']),
    countryList () {
      let array = [
        {name_en: "other"}
      ]
      return this.siteList.concat(array)
    },
    isFull () {
      let isFull = true
      let country =  this.form.country.length > 0
      let email = this.form.email.length > 0
      let nickname = this.form.nickname.length > 0
      let active_device = this.form.active_device.length > 0
      let is_share_ideas = this.form.is_share_ideas.length > 0
      let is_kept_confidential = this.form.is_kept_confidential.length > 0
      let evaluate_products = this.form.evaluate_products.length > 0
      
      if (country && email && nickname && active_device && is_share_ideas && is_kept_confidential && evaluate_products){
        // this.$refs.form.validate((valid) => {
        //   if(valid){
        //     isFull =  true
        //   } 
        // })
        let array = ['country', 'email', 'nickname', 'active_device','is_share_ideas', 'is_kept_confidential', 'evaluate_products']
        if(this.curEmail.sign_up == 0){
          array.push('password')
          array.push('confirmPwd')  
        }
        this.$refs.form.validateField(array, (msg)=>{
          isFull = isFull && !msg
        })
      } else {
        isFull = false
      }
      return isFull
    }
  },
  watch:{
    userInfo(){
      this.setFormData()
    }
  },
  mounted (){
    this.setFormData()
    this.$emit("setHeight")
  },
  methods: {
    goToLogIn () {
      this.$router.push('/login')
    },
    setFormData(){
      
      if(this.userInfo.country){
        this.form.country = this.userInfo.country
      }  
      if(this.userInfo.nickname){
        this.form.nickname = this.userInfo.nickname
      }  
      if(this.userInfo.email){
        this.form.email = this.userInfo.email
      } 
      if(this.userInfo.is_share_ideas){
        this.form.is_share_ideas = this.userInfo.is_share_ideas
      } 
      if(this.userInfo.is_kept_confidential){
        this.form.is_kept_confidential = this.userInfo.is_kept_confidential
      } 

      let device = this.userInfo.active_device
      if(device){
        if(device.indexOf(',') > -1){
          device = device.split(',')
        }else {
          let array = []
          array.push(device)
          device = array
        }
        this.form.active_device = device
      } 
      let product = this.userInfo.evaluate_products
      if(product){
        if(product.indexOf(',') > -1){
          product = product.split(',')
        }else {
          let array = []
          array.push(product)
          product = array
        }
        this.form.evaluate_products = product
      } 
    },
    getEmailStatus (event) {
      event.target.blur();
      this.$refs.form.validateField('email', (msg)=>{
        if(!msg){
          this.getEmail()
        }
      })
    },
    getEmail(){
      let params = {
        email:this.form.email
      }
      allEmailGet(params).then(res=>{
        this.curEmail = res.data
        if(res.data.sign_up == 1 ){
          this.isInfoShow = true
        }
      })
    },
    changeEmail (value) {
      let emailList = this.emailList
      for (let i = 0; i < emailList.length; i++ ){
        if (emailList[i].value == value){
          this.curEmail = emailList[i]
        }
      }
      this.form.password = ''
      this.form.confirmPwd = ''
    },
    isConfirmPswShow () {
      if(this.showConfirmPsw == 'password'){
        this.showConfirmPsw = 'text'
      } else {
        this.showConfirmPsw = 'password'
      }
    },
    isPswShow () {
      if(this.showPsw == 'password'){
        this.showPsw = 'text'
      } else {
        this.showPsw = 'password'
      }
    },
    submitForm() {
      let isFull = true
      let array = ['country', 'nickname', 'email', 'active_device','is_share_ideas','is_kept_confidential', 'evaluate_products']
      if(this.curEmail.sign_up == 0){
        array.push('password')
        array.push('confirmPwd')  
      }
      this.$refs.form.validateField(array, (msg)=>{
        isFull = isFull && !msg
        this.isFull = isFull
       
      })
       if(isFull){
          this.signUp()
        }
    },
    signUp(){
      this.isRequest = true
      let params = this.form
      params.language = this.curSite.site
            params.local_time = timeFormat(new Date()).split(' ')[0],
      betaTester(params).then(res=>{
       if(res.state == 1 ){
          let data =res.data
          if(data.b_status == 1){ // 订阅
            this.isInfoShow = true
          } else if (data.b_status == 2){// 取消订阅
            this.isGuideShow = true
          } else { // warranty 为空 
            if(data.email_is_valid ==1){//邮箱有效
              if(data.w_status == 0){
                this.$router.push('/warranty_guide')
              }else if(data.w_status == 2){
                this.$router.push('/warranty_active_guide')
              }else if(data.w_status == 1){
                this.$router.push('/betatester_success')
              }
            }else if(data.email_is_valid ==2){//邮箱无效
              this.$router.push('/register_email')
            }

          }
        }
        this.$store.dispatch('GetUserInfo')
        this.isRequest = false
      })
    },
   
  }
}
</script>

<style lang="scss">
@import '@/styles/register/register.scss';
.betaTester{
  .title{
    margin-bottom: 16px;
  }
  .secTitleGuide{
    color: #666;
    font-size: 14px;
    margin-bottom: 16px;
    text-align: center;
    >span{
      margin-left: 40px;
      cursor: pointer;
      color: #0B95FD;
    }
  }
  .el-form-item:last-of-type{
    margin-bottom: 40px;
  }
}


</style>